package com.lzh.chatnote.user.controller;

import cn.hutool.core.util.RandomUtil;
import com.lzh.chatnote.common.domain.response.ApiResult;
import com.lzh.chatnote.user.service.WxMsgService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpQrCodeTicket;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.view.RedirectView;

import javax.servlet.http.HttpSession;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 微信回调接口
 */
@Slf4j
@AllArgsConstructor
@RequestMapping("wx/public")
@RestController
@Api(value = "微信扫码接口")
public class WxController {
    private static final ConcurrentHashMap<Integer, HttpSession> WAIT_LOGIN_MAP = new ConcurrentHashMap<>();
    private final WxMpService wxMpService;
    private final WxMpMessageRouter messageRouter;
    private final WxMsgService wxMsgService;

    /**
     * test配置微信公众号的接口
     * @param signature
     * @param timestamp
     * @param nonce
     * @param echostr
     * @return
     */
    @ApiOperation(value = "微信扫码登录接口")
    @GetMapping(produces = "text/plain;charset=utf-8")
    public String authGet(@RequestParam(name = "signature", required = false) String signature,
                          @RequestParam(name = "timestamp", required = false) String timestamp,
                          @RequestParam(name = "nonce", required = false) String nonce,
                          @RequestParam(name = "echostr", required = false) String echostr) {
        log.info("\n接收到来自微信服务器的认证消息：[{}, {}, {}, {}]", signature, timestamp, nonce, echostr);
        if (StringUtils.isAnyBlank(signature, timestamp, nonce, echostr)) {
            throw new IllegalArgumentException("请求参数非法，请核实!");
        }

        if (wxMpService.checkSignature(timestamp, nonce, signature)) {
            return echostr;
        }

        return "非法请求";
    }


    /**
     * 用户扫码登录微信服务器后回调接口
     * @param code
     * @return
     * @throws WxErrorException
     */
    @GetMapping("/callBack")
    public RedirectView callBack(@RequestParam String code){
        /**
         * (openid=omsFk6UzbGXG1mdzE6lIOuaqE0eM, nickname=ikun, sex=0, city=, province=, country=,
         * headImgUrl=https://thirdwx.qlogo.cn/mmopen/vi_32/TUNjfpwYXUSVbBkqrMiapnQ28Tg5UTWDvtagFZusn3BWO1wMoGrBQ6WQNc4hNqE7aMrEc8UvXglwngfATiaPwGEKdW86vA8mp1WqDXNXOkVn4/132,、
         * unionId=null,
         * privileges=[],
         * snapshotUser=null)
         */
        try {
            WxOAuth2AccessToken accessToken = wxMpService.getOAuth2Service().getAccessToken(code);
            WxOAuth2UserInfo userInfo = wxMpService.getOAuth2Service().getUserInfo(accessToken, "zh_CN");
            //log.info("接收到userInfo信息========>"+userInfo);
            //获取微信授权信息，保存用户信息
            wxMsgService.authorize(userInfo);
        } catch (Exception e) {
            log.error("callBack error", e);
        }
        RedirectView redirectView = new RedirectView();
        redirectView.setUrl("https://mp.weixin.qq.com/s?__biz=MzkwOTUwNDY0NQ==&mid=2247483660&idx=1&sn=c450dfb9a4a8f6d2a486bd25f30d1c24&chksm=c138f8e6f64f71f039646c016864e4b13b994fdd3dfbc26e6813a29ba693357642f3fd845d77#rd");
        return redirectView;
    }

    /**
     * test 用户扫码登录接口 获取二维码登录地址
     */
    @RequestMapping(value = "/login",method = RequestMethod.GET)
    public ApiResult<String> scanCodeLogin(HttpSession httpSession) throws WxErrorException {
        Integer code = generateLoginCode(httpSession);
        //请求微信接口，获取登录码地址
        WxMpQrCodeTicket wxMpQrCodeTicket = wxMpService.getQrcodeService().qrCodeCreateTmpTicket(code, 600);
        ApiResult<String> ResponseResult = new ApiResult<>();
        ResponseResult.setData(wxMpQrCodeTicket.getUrl());
        return ResponseResult;
    }

    private Integer generateLoginCode(HttpSession httpSession) {
        int code;
        do {
            code = RandomUtil.randomInt(Integer.MAX_VALUE);
        } while (WAIT_LOGIN_MAP.contains(code)
                || Objects.nonNull(WAIT_LOGIN_MAP.putIfAbsent(code, httpSession)));
        return code;
    }

    /**
     * 1.首先使用websocket获取微信二维码或者第三方登录（url）保存 code - channel 连接关系
     *
     * 微信公众号里发送消息会根据不同的消息触发不同的事件处理器去处理消息 （扫码功能就是监听扫码处理器，获取openid和code的绑定关系）
     *
     * 3.最后回调获取openid - channel的关联
     * @param requestBody
     * @param signature
     * @param timestamp
     * @param nonce
     * @param openid
     * @param encType
     * @param msgSignature
     * @return
     */
    @PostMapping(produces = "application/xml; charset=UTF-8")
    public String post(@RequestBody String requestBody,
                       @RequestParam("signature") String signature,
                       @RequestParam("timestamp") String timestamp,
                       @RequestParam("nonce") String nonce,
                       @RequestParam("openid") String openid,
                       @RequestParam(name = "encrypt_type", required = false) String encType,
                       @RequestParam(name = "msg_signature", required = false) String msgSignature) {

        //todo 缓存
        //这里需要管理openid和code关系
        //放到redis缓存里面
        log.info("\n接收微信请求：[openid=[{}], [signature=[{}], encType=[{}], msgSignature=[{}],"
                        + " timestamp=[{}], nonce=[{}], requestBody=[\n{}\n] ",
                openid, signature, encType, msgSignature, timestamp, nonce, requestBody);

        if (!wxMpService.checkSignature(timestamp, nonce, signature)) {
            throw new IllegalArgumentException("非法请求，可能属于伪造的请求！");
        }

        String out = null;
        if (encType == null) {
            // 明文传输的消息
            WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(requestBody);
            WxMpXmlOutMessage outMessage = this.route(inMessage);
            if (outMessage == null) {
                return "";
            }

            out = outMessage.toXml();
        } else if ("aes".equalsIgnoreCase(encType)) {
            // aes加密的消息
            WxMpXmlMessage inMessage = WxMpXmlMessage.fromEncryptedXml(requestBody, wxMpService.getWxMpConfigStorage(),
                    timestamp, nonce, msgSignature);
            log.debug("\n消息解密后内容为：\n{} ", inMessage.toString());
            WxMpXmlOutMessage outMessage = this.route(inMessage);
            if (outMessage == null) {
                return "";
            }

            out = outMessage.toEncryptedXml(wxMpService.getWxMpConfigStorage());
        }

        log.debug("\n组装回复信息：{}", out);
        return out;
    }

    private WxMpXmlOutMessage route(WxMpXmlMessage message) {
        try {
            return this.messageRouter.route(message);
        } catch (Exception e) {
            log.error("路由消息时出现异常！", e);
        }
        return null;
    }




}
